package com.zy.filter;

import com.alibaba.fastjson.JSONObject;
import com.zy.constant.AuthConstants;
import com.zy.model.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * token转换过滤器
 */
@Component
public class TokenTranslationFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * token转换过滤器
     * 前提：
     *      只负责处理携带token的请求，然后将认证的用户信息转换出来
     *      没有携带token的请求交给Security资源服务配置类的处理器处理(ResourceServerConfig.class)
     *
     * 流程：
     *      1.获取token
     *      2.判断token是否有值
     *          有：
     *              token转换为用户信息
     *              将用户信息转换为Security框架认识的用户信息对象(UserDetails)
     *              再将认识的用户信息对象存放到当前资源服务的上下文中
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //请求头中获取Authorization的值，格式为"bearer token"
        String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
        if (StringUtils.hasText(authorization)) {
            //获取token，得到已转为json字符串格式的userJsonStr
            String token = authorization.replaceFirst(AuthConstants.BEARER, "");
            //判断token是否有值
            if (StringUtils.hasText(token)) {
                //token续期
                //从redis中获取token的剩余存活时长
                Long tokenExpire = stringRedisTemplate.getExpire(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                if (tokenExpire <= AuthConstants.TOKEN_EXPIRE_THRESHOLD_TIME) {
                    //续期，重新设置为4小时
                    stringRedisTemplate.expire(AuthConstants.LOGIN_TOKEN_PREFIX+token, AuthConstants.TOKEN_TIME, TimeUnit.SECONDS);
                }

                //从redis中获取json字符串的用户认证信息
                String userJsonStr = stringRedisTemplate.opsForValue().get(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                //将json格式字符串的用户认证信息转换用户认证对象
                SecurityUser securityUser = JSONObject.parseObject(userJsonStr, SecurityUser.class);

                //获取权限集合
                Set<SimpleGrantedAuthority> permCollect = securityUser.getPerms().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
                //创建UsernamePasswordAuthenticationToken对象
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser, null, permCollect);
                //将用户认证对象存放到当前模块的上下文中
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
